package IEFYP.JunkCallFiltering;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;


public class DBhelper {
	private static final String TAG = "DBHelper";
    private static String DB_PATH = "/data/data/IEFYP.JunkCallFiltering/databases/";
    private static String DB_NAME = "junkcallkiller.db";
    private String table; 
	SQLiteDatabase db;
	Context context;
	
	DBhelper(Context _context, String _table) {
		context = _context;
		table = _table;
	}
	
	public void OpenDB(){
		try{
			createDataBase();
		}catch(IOException e){
			throw new Error("Error copying database");
		}		
		db = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE,null);
		Log.v(TAG, "db path=" + db.getPath());
	}

    public void createDataBase() throws IOException{
    	 
    	boolean dbExist = checkDataBase();
 
    	if(dbExist){
    		//do nothing - database already exist
    		Log.v(TAG, "db is existed");
    	}else{
 
    		context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
        	try {
 
    			copyDataBase();
 
    		} catch (IOException e) {
 
        		throw new Error("Error copying database");
 
        	}
    	}
    }
    
    private boolean checkDataBase(){ //Check the existence of the database
    	 
    	SQLiteDatabase checkDB = null;
 
    	try{
    		String myPath = DB_PATH + DB_NAME;
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    	}catch(SQLiteException e){
 
    		//database does't exist yet.
    	 return false;
 
    	}
 
    	if(checkDB != null){ 
    		checkDB.close(); 
    	} 
    	return checkDB != null ? true : false;
    }
    
    private void copyDataBase() throws IOException{ //copying the database from Assets to system
    	 
    	//Open your local db as the input stream
    	InputStream myInput = context.getAssets().open(DB_NAME);
 
    	// Path to the just created empty db
    	String outFileName = DB_PATH + DB_NAME;
 
    	//Open the empty db as the output stream
    	OutputStream myOutput = new FileOutputStream(outFileName);
 
    	//transfer bytes from the inputfile to the outputfile
    	byte[] buffer = new byte[1024];
    	int length;
    	
    	while ((length = myInput.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}
 
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
    }
    
   
    /*
	public void CreateTable() {
		try {
			db.execSQL("CREATE TABLE blacklist (_id INTEGER PRIMARY KEY, call_no TEXT, type TEXT, isblocked NUMERIC);" ); 
			Log.v(TAG, "Create Table t_user ok");
		} catch (Exception e) {
			Log.v(TAG, "Create Table t_user err,table exists.");
		}
	}
	*/
	

	
	public boolean insert(String callno,String type,int isblocked){
    	try{

    	//	db.execSQL("INSERT INTO '"+table+"' VALUES(null,'"+callno+"','"+type+"',"+isblocked+");");
    		db.execSQL("INSERT INTO 'userlist' VALUES(null,'"+callno+"','"+type+"',"+isblocked+");");
    			        Log.v(TAG,"insert Table t_user ok");
	        return true;
	       
        }catch(Exception e){
        	Log.v(TAG,"update Table t_user err ,sql: "+e.toString());
        	return false;
        }
    }
	
	public boolean delete(String callno){
    	try{

    		db.delete("userlist", "call_no ='"+callno+"'", null);
    		//db.rawQuery("INSERT INTO userlist (call_no,type,isblocked)"+" VALUES('"+callno+"','"+type+"',"+isblocked+")", null);
    			        Log.v(TAG,"Delete Table userlist ok");
	        return true;
	       
        }catch(Exception e){
        	Log.v(TAG,"Delete Table userlist err ,sql: "+e.toString());
        	return false;
        }
    }

	public boolean update(String callno,String key,String value){
    	try{
  //  		db.execSQL("UPDATE '"+table+"' SET '"+key+"'='"+value+"'WHERE 'call_no'='"+callno+"';");
  //  		String query = "UPDATE '"+table+"' SET '"+key+"'='"+value+"'WHERE 'call_no'='"+callno+"'";
    		ContentValues values = new ContentValues();
    		values.put(key, value);
    	
    		db.update(table, values, "call_no='"+callno+"'", null);
	      
	        Log.v(TAG,"insert Table t_user ok"+key+" "+ value+";");
	        return true;
	        
        }catch(Exception e){
        	Log.v(TAG,"insert Table t_user err ,sql: "+e.toString());
        	return false;
        }
	}
	
	public boolean update(String callno,String key,boolean ivalue){
    	try{
    		int value;
    		if(ivalue){
    			value = 1;
    		}else{
    			value =0;
    		}
    		ContentValues values = new ContentValues();
    		values.put(key, value);
    	     
    		if(callno == null){
    			db.update(table, values, null, null);
    		}else{
    			db.update(table, values, "call_no='"+callno+"'", null);
    		}
  //  		db.execSQL("UPDATE '"+table+"' SET '"+key+"'='"+value+"'WHERE 'call_no'='"+callno+"';");
  //  		String query = "UPDATE '"+table+"' SET '"+key+"'= "+value+" WHERE 'call_no'='"+callno+"'";
  //  		db.rawQuery(query, null);
    		
	        Log.v(TAG,"insert Table t_user ok"+key+" "+ value+";");
	        return true;
	        
        }catch(Exception e){
        	Log.v(TAG,"insert Table t_user err ,sql: "+e.toString());
        	return false;
        }
	}
	
	public Cursor loadAll(){
		
		Cursor cur=db.query(table, null,null ,null, null, null, null);
		
		return cur;
	}
	
	
	public boolean checkBlocked(String callno){
		
			Cursor cur;		
				cur = db.rawQuery("SELECT isblocked FROM "+table+" WHERE call_no="+callno, null);
			//query(table, null,null ,null, null, null, null);//new String[] {"call_no"} "'call_no' = '"+callno+"'"
				cur.moveToFirst();	
    			int result = cur.getInt(0);
    			Log.v(TAG,"number: "+callno+", isblocked: "+result);
    			if(result == 1){
    				return true;
    			}else{
    				return false;
    			}
    		 		
		
	}
	public String findNumber(String callno, boolean checkBlocked){ // Find out whether the number is in the list or not
			if(callno != null){
				Cursor cur;
				if(checkBlocked){ 
					cur = db.rawQuery("SELECT call_no FROM "+table+" WHERE call_no='"+callno+"' AND isblocked = 1", null);
				//query(table, null,null ,null, null, null, null);//new String[] {"call_no"} "'call_no' = '"+callno+"'"
				}else{
					cur = db.rawQuery("SELECT call_no FROM "+table+" WHERE call_no='"+callno+"'", null);
				}
				
				if(cur.moveToFirst()){
	    			int col = cur.getColumnIndex("call_no");
	    			String result = cur.getString(col);
	    			Log.v(TAG,"findNumber ok, table:"+result);
	    			return result;
	    		}else{
	    			Log.v(TAG,"findNumber err ,table: "+table);
	    			return "NULL";
	    		}
			}else{
				return "NULL";
			}
        
	}
	
	
	public void close(){
		db.close();
	}
}
